<template>
  <div class="categories">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加商品分类 -->
    <el-button type="primary" plain @click="handleAddCate">添加分类</el-button>

    <!-- 树形列表组件 -->
    <tree-grid
      v-loading='loading'
      class="mt-15 mb-15"
      :treeStructure="true"
      :columns="columns"
      :data-source="dataSource"
      @deleteCate="deleteCategory"
      @editCate="editCategory"
    >
    </tree-grid>

      <!-- 分页 -->
    <el-pagination
      class="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pagesize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 添加分类弹框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogFormVisible">
      <!-- addForm表单数据，:rules属性传入校验规则，prop指定需要校验的字段名 -->
      <el-form :model="addCateForm" :rules="addcaterules" ref="addCateRef">
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="cat_name">
          <el-input v-model="addCateForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" :label-width="formLabelWidth">
          <!-- 级联选择器 -->
          <el-cascader
            change-on-select
            :props="props"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmAddCate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑分类弹框 -->
    <el-dialog title="编辑分类" :visible.sync="editCateDialogFormVisible">
      <!-- addForm表单数据，:rules属性传入校验规则，prop指定需要校验的字段名 -->
      <el-form :model="editCateForm" :rules="addcaterules" ref="editCateRef">
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="cat_name">
          <el-input v-model="editCateForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmEditCate">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import TreeGrid from '@/components/TreeGrid/TreeGrid'
import { getCategories, addCategories, deleteCategories, editCategories, getCategoriesById } from '@/api'
export default {
  components: {
    TreeGrid
  },
  data () {
    return {
      loading: false, // 加载动画
      dataSource: [], // 表格数据源
      // 渲染的列
      columns: [{
        text: '分类名称',
        dataIndex: 'cat_name',
        width: ''
      }, {
        text: '是否有效',
        dataIndex: 'cat_deleted',
        width: ''
      }, {
        text: '排序',
        dataIndex: 'cat_level',
        width: ''
      }],
      currentPage: 1, // 当前页码
      total: 0, // 数据总条数
      pagesize: 10, // 每页默认10条
      pagenum: 1, // 默认第一页
      addCateDialogFormVisible: false, // 弹框显示
      formLabelWidth: '20%', // 弹框宽度
      // 添加分类表单
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      // 规则
      addcaterules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 数据
      options: [],
      // 级联选择器配置
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器
      selectedOptions: [],
      // 编辑分类
      editCateForm: {
        cat_name: '',
        cat_id: ''
      },
      editCateDialogFormVisible: false
    }
  },
  mounted () {
    this.initTable()
  },
  methods: {
    // 初始化表格
    initTable () {
      this.loading = true
      // 获取商品列表, 参数：获取第几层数据，pagesize，pagenum
      getCategories(3, this.pagesize, this.pagenum).then(res => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          this.total = res.data.data.total
          this.dataSource = res.data.data.result
        } else {
          this.$message.error(res.data.meta.msg)
        }
        this.loading = false
      }).catch(err => {
        console.log(err)
      })
    },
    // 删除分类
    deleteCategory (cid) {
      this.$confirm('是否删除该商品分类？', '注意', {
        confirmButtonText: '删除',
        cancelButtonTet: '取消',
        type: 'warning'
      }).then(() => {
        deleteCategories(cid).then(res => {
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.initTable()
          } else {
            this.$message.error(res.data.meta.msg)
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 编辑分类
    editCategory (cid) {
      // console.log(cid)
      this.editCateDialogFormVisible = true
      getCategoriesById(cid).then(res => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          this.editCateForm.cat_id = res.data.data.cat_id
          this.editCateForm.cat_name = res.data.data.cat_name
        } else {
          this.$message.error(res.data.meta.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 确认编辑分类
    confirmEditCate () {
      editCategories(this.editCateForm).then(res => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          this.editCateDialogFormVisible = false
          this.$message.success(res.data.meta.msg)
          this.initTable()
        } else {
          this.$message.error(res.data.meta.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 每页条数
    handleSizeChange (val) {
      // console.log(val)
      this.pagesize = val
      this.initTable()
    },
    // 跳转页码
    handleCurrentChange (val) {
      // console.log(val)
      this.pagenum = val
      this.currentPage = val
      this.initTable()
    },
    // 添加分类弹框
    handleAddCate () {
      this.addCateDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.addCateRef.clearValidate()
      })
      getCategories(3).then(res => {
        console.log(res)
        if (res.data.meta.status === 200) {
          this.options = res.data.data
        } else {
          this.$message.error(res.data.meta.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 确认提交分类
    confirmAddCate () {
      this.$refs.addCateRef.validate(isPass => {
        if (isPass) {
          addCategories(this.addCateForm).then(res => {
            // console.log(res)
            if (res.data.meta.status === 201) {
              this.addCateForm.cat_name = ''
              this.addCateForm.cat_pid = ''
              this.addCateForm.cat_level = ''
              this.selectedOptions = []
              this.addCateDialogFormVisible = false
              this.$message.success(res.data.meta.msg)
              this.initTable()
            } else {
              this.$message.error(res.data.meta.msg)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 级联选择器改变则触发该函数
    handleChange (val) {
      /**
       * 对val的长度进行判断，默认为 cat_level=0
       * 如果val.length===1，说明创建的是二级节点，此时cat_level=1
       * 如果val.length===2，说明创建的是三级节点，此时cat_level=2
       */
      if (val.length === 1) {
        // 当前选择的层级
        this.addCateForm.cat_level = 1
        // 当前选择的父层级id
        this.addCateForm.cat_pid = val[0]
      } else {
        this.addCateForm.cat_level = 2
        this.addCateForm.cat_pid = val[1]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-cascader {
  width: 100%;
}
</style>
